package com.atshangluo.oss.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.atshangluo.oss.service.OssService;
import com.atshangluo.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName OssServiceImpl.java
 * @Description TODO
 * @createTime 2021年07月26日 12:17:00
 */
@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        //获取阿里云存储相关常量
        String endPoint = ConstantPropertiesUtil.END_POINT;

        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;

        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;

        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        String uploadUrl = null;


        try {
            OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
//            if (!ossClient.doesBucketExist(bucketName)){
                //创建bucket
                ossClient.createBucket(bucketName);
                //设置oss实例的访问权限：公共读
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
//            }
            InputStream inputStream = file.getInputStream();
            //构建日期路径：avatar/2019/02/26/文件名
            String filePath = new DateTime().toString("yyyy/MM/dd");
            //文件名：uuid.扩展名
            String original = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString();
            String fileType = original.substring(original.lastIndexOf("."));
            String newName =  filePath+"/"+fileName + fileType;
            String fileUrl =  "https://"+bucketName+"."+endPoint + "/"+ newName;

            ossClient.putObject(bucketName,newName,inputStream);

            return fileUrl;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }
}
